
import { makeAutoObservable } from "mobx";
import React from "react";
import * as apis from "@shared/apis";

export class PageController {

    static Context = React.createContext<PageController>(undefined as any);

    /** 当前页码 */
    page = 1;

    /** 每页数量 */
    pageSize = 10;

    /** 搜索关键词 */
    keyword = '';

    /** 总数量 */
    total = 1;

    /** 是否加载中 */
    loading = 0;

    /** 客户列表 */
    data: apis.customers.ICustomer[] = [];

    constructor() {
        makeAutoObservable(this);
    }

    /** 查询指定页码的数据 */
    query = async () => {
        if (this.loading > 0 || this.data.length >= this.total) return;
        try {
            this.loading++;
            const { page, pageSize, keyword } = this;
            const res = await apis.customers.list.post({ page, pageSize, keyword });
            this.data = [...this.data, ...res.items];
            this.total = res.pagination.total;
        } catch (error) {
            console.log(error);
        }
        finally {
            this.loading--;
        }
    }

    /** 设置 搜索关键词 */
    setKeyword = (keyword: string) => {
        this.keyword = keyword;
        this.page = 1;
        this.total = 1;
        this.data = [];
        this.query();
    }
}


